package com.pat.web.controller;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.model.Message;

public class MessageController extends Controller {

	public void getMessages() {
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		List<Message> messages = Message.dao.find("select * from message where user_id = ? order by create_time desc",
				userId);
		ApiResponse response = new ApiResponse();
		response.setData(messages);
		response.setStatusCode("0000");
		renderJson(JSON.toJSONString(response, SerializerFeature.WriteDateUseDateFormat));
		// 设置消息为已读
		Db.update("update message set `read` = 1 where user_id = ?", userId);
	}

	public void countUnreadMessage() {
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		long message = Db.queryLong("select count(*) from message where user_id = ? and `read` = 0", userId);
		ApiResponse response = new ApiResponse();
		response.setData(message);
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void delMessage() {
		Long[] messageIds = getParaValuesToLong("id");
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		if (messageIds != null && messageIds.length > 0) {
			for (Long messageId : messageIds) {
				Db.update("delete from message where id = ? and user_id = ?", messageId, userId);
			}
		}
		ApiResponse response = new ApiResponse();
		response.setData("success");
		response.setStatusCode("0000");
		renderJson(response);
	}
}
